package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Administrator
 * Date: 2023-01-14
 * Time: 上午 0:10
 */
@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        String blogID = req.getParameter("blogID");
        BlogDao blogs = new BlogDao();
        if(blogID == null) {
            //获取博客列表,并转换成json格式的字符串
            List<Blog> list = blogs.selectAll();
            String str = objectMapper.writeValueAsString(list);
            resp.getWriter().write(str);
        }else {
            //获取博客详情页
            Blog blog = blogs.selectOne(Integer.parseInt(blogID));
            String detailJson = objectMapper.writeValueAsString(blog);
            resp.getWriter().write(detailJson);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");

        //判断用户是否登录
        HttpSession session = req.getSession(false);
        if(session == null) {
            resp.setStatus(403);
            return;
        }

        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            return;
        }

        //获取提交的正文
        String title = req.getParameter("title");
        String content = req.getParameter("content");

        if(title == null || content == null || title.equals("") || content.equals("")) {
            resp.setStatus(400);
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("输入信息不完整!");
            return;
        }

        //把正文写入到博客对象当中
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserID(user.getUserID());
        //把博客对象插入数据库
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);

        resp.sendRedirect("blog_list.html");
    }
}
